import os
import pandas as pd
import numpy as np

def check_sku_whether_in_ignores(xls):
    # 检查待上线SKU是否在-1或者10000（负样本）里！当ignores包含这两者时会过滤加载
    xlsc = pd.read_excel(xls)
    tid2lbs = {}
    onlines = []
    ignores = []
    for row in xlsc.iloc():
        tid, label = str(row[0]), str(row[-1])
        if tid in ('10000', '-1'):
            ignores.append(label)
            continue
        onlines.append(label)
        if tid not in tid2lbs:
            tid2lbs[tid] = [label]
        else:
            tid2lbs[tid] += [label]
            
    ols = set(onlines)
    for ignore in ignores:
        if ignore in ols:
            print(ignore)    

def get_recall_precision(result):
    result = pd.read_excel(result)
    recalls = []
    precisions = []
    for row in result.iloc():
        label = str(row[0])
        if label in ('nan', ''):
            continue
        recall = row[4]
        precision = row[5]
        recalls.append(recall)
        precisions.append(precision)
    return np.mean(recalls), np.mean(precisions)

def compare_detection_results_between_two_version(results_v1_src, results_v2_src, dst=None):
    results_v1 = [f for f in os.listdir(results_v1_src) if f.endswith('.xlsx')]
    results_v2 = [f for f in os.listdir(results_v2_src) if f.endswith('.xlsx')]
    
    assert len(results_v2) == len(results_v1), '新旧目录下必须分别存放相同租户的识别结果.xlsx，数量一致，不能存放任何其他xlsx文件。'
    results_v1.sort()
    results_v2.sort()
    
    compare_results = dict(tenantId=[], recall_v1=[], precision_v1=[], recall_v2=[], precision_v2=[])
    for result_v1, result_v2 in zip(results_v1, results_v2):
        assert result_v1 == result_v2
        tenantId = os.path.splitext(result_v1)[0]
        result_v1 = get_recall_precision(os.path.join(results_v1_src, result_v1))
        result_v2 = get_recall_precision(os.path.join(results_v2_src, result_v2))
        compare_results['tenantId'].append(tenantId)
        compare_results['recall_v1'].append(result_v1[0])
        compare_results['precision_v1'].append(result_v1[1])
        compare_results['recall_v2'].append(result_v2[0])
        compare_results['precision_v2'].append(result_v2[1])    
    
    compare_results = pd.DataFrame(compare_results)
    
    print(compare_results)
    if dst in ('', None):
        dst = os.path.join(results_v2_src, 'compare_results')
        if not os.path.exists(dst):
            os.makedirs(dst)
        dst = os.path.join(dst, 'evaluate_v1&v2_results.xlsx')
    
    compare_results.to_excel(dst, index=None)
    print('新旧模型识别率对比结果保存至', dst)
